package arisufascion.com.compone;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;
import android.widget.LinearLayout;
import arisufascion.com.R;

public class PagingView extends LinearLayout {

	private int pageNo = 1;

	private int current;

	private Drawable activeImage;

	private Drawable nonactiveImage;

	private int childPadding;

	public PagingView(Context context) {
		super(context);
		this.init(context, null);
	}

	public PagingView(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.init(context, attrs);
	}

	private void init(Context context, AttributeSet attrs) {
		setOrientation(LinearLayout.HORIZONTAL);
		TypedArray typed = context.obtainStyledAttributes(attrs, R.styleable.PagingView);
		activeImage = typed.getDrawable(R.styleable.PagingView_activeImage);
		nonactiveImage = typed.getDrawable(R.styleable.PagingView_nonactiveImage);
		childPadding = typed.getDimensionPixelSize(R.styleable.PagingView_childPadding, 12);
	}

	public void build(int pageCount) {
		this.pageNo = pageCount;
		removeAllViews();
		for (int i = 0; i < pageNo; i++) {
			ImageView view = new ImageView(getContext());
			view.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
			view.setPadding(childPadding, childPadding, childPadding, childPadding);
			if (i == 0) {
				view.setImageDrawable(activeImage);
			} else {
				view.setImageDrawable(nonactiveImage);
			}
			addView(view);
		}
	}

	public void showNext() {
		if (current < getChildCount() - 1) {
			ImageView view = (ImageView) getChildAt(current);
			view.setImageDrawable(nonactiveImage);

			current++;
			view = (ImageView) getChildAt(current);
			view.setImageDrawable(activeImage);
		}
	}

	public void showPreview() {
		if (0 < current) {
			ImageView view = (ImageView) getChildAt(current);
			view.setImageDrawable(nonactiveImage);

			current--;
			view = (ImageView) getChildAt(current);
			view.setImageDrawable(activeImage);
		}
	}

	public void setPosition(int position) {
		if (current == position) {
			return;
		}
		if (position < 0) {
			position = 0;
		}
		if (getChildCount() <= position) {
			position = getChildCount() - 1;
		}

		if (0 <= position && position <= getChildCount() - 1) {
			ImageView view = (ImageView) getChildAt(current);
			view.setImageDrawable(nonactiveImage);

			current = position;
			view = (ImageView) getChildAt(current);
			view.setImageDrawable(activeImage);
		}
	}
}
